package edu.zut.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//登录拦截过滤器，如果用户未登录，禁止用户访问应用，如果已登录，允许
@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //登录的自动拦截过滤
        String path = req.getServletPath();
        System.out.println("path = " + path);
//        String uri = req.getRequestURI();
        //将用户需要登录后访问的资源统一拦截
        if (!(path.contains("login") || path.contains("index"))){
            //判断用户是否登录
            Object status = req.getSession().getAttribute("loginStatus");
            if (status == null || !status.equals("true")){
                req.setAttribute("error","请先登录后访问");
                req.getRequestDispatcher("/view/login.jsp").forward(req,resp);
            }
        }
        chain.doFilter(request, response);
    }
}
